﻿using Abp.Application.Services.Dto;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Akso.Entities;
using Akso.Inbounds.Dto;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Dynamic;
using Abp.Linq.Extensions;
using Abp.AutoMapper;
using Abp.Authorization;
using Akso.Authorization;

namespace Akso.Inbounds
{
    [AbpAuthorize(AppPermissions.Pages_Inventory_Inbounds)]
    public class InboundAppService: AbpZeroTemplateAppServiceBase, IInboundAppService
    {
        //在接口中的引用的方法在这个地方必须都要定义，否则IInboundAppService会报错


        private readonly IRepository<Inbound, Guid> _inboundsRepository;
        //private readonly IInboundListExcelExporter _inboundListExcelExporter;

        public InboundAppService(IRepository<Inbound, Guid> inboundsRepository)
        {
            _inboundsRepository = inboundsRepository;
        }
        public async Task<PagedResultOutput<InboundListDto>> GetObjects(GetInboundsInput input)
        {
            var query = getQuery(input);
            var dataCount = await query.CountAsync();
            var data = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();

            return new PagedResultOutput<InboundListDto>(
                dataCount,
                data.MapTo<List<InboundListDto>>()
                );
        }

        private IQueryable<Inbound> getQuery(GetInboundsInput input)
        {
            var query = _inboundsRepository.GetAll()
                .WhereIf(
                    !input.Filter.IsNullOrWhiteSpace(),
                    t =>
                        t.Vendor.Contains(input.Filter) ||
                        t.MaterialNameCn.Contains(input.Filter)
                );
            return query;
        }
        //删除记录
        [AbpAuthorize(AppPermissions.Pages_Inventory_Inbounds_Delete)]
        public async Task DeleteObject(IdInput<Guid> input)
        {
            var o = await _inboundsRepository.GetAsync(input.Id);
            await _inboundsRepository.DeleteAsync(o);
        }
        [AbpAuthorize(AppPermissions.Pages_Inventory_Inbounds_Create,AppPermissions.Pages_Inventory_Inbounds_Edit)]
        public async Task<GetInboundForEditOutput> GetObjectForEdit(NullableIdInput<Guid> input)
        {
            var output = new GetInboundForEditOutput
            {

            };
            if(!input.Id.HasValue)
            {
                output.Inbound = new InboundEditDto();
            }
            else
            {
                var inbound = await _inboundsRepository.GetAsync(input.Id.Value);
                output.Inbound = inbound.MapTo<InboundEditDto>();
            }
            return output;
        }
    }
}
